<?php
//培训管理
namespace app\admin\controller;
use Download\FileDownload;
use think\Db;
use app\admin\validate\KnowledgeValidate;
class TrainController extends CommonController {

    /**
     * 获取试题数据
     */
    public function getInfo(){
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if($_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['a.exam_name|u.user_username'] = array('like',"%$keyword%");
        }

        if($_POST['exam_status']!=''){//状态
            $where['a.exam_status'] = $_POST['exam_status'];
        }
        if($_POST['start']!=''){//时间
            $where['a.exam_time'] =array('>=',$_POST['start']);
        }elseif ($_POST['end']!=''){
            $where['a.exam_time'] =array('<=',$_POST['end']);
        }elseif ($_POST['start']!=''&&$_POST['end']!=''){
            $where['a.exam_time'] =array('between',array($_POST['start'],$_POST['end']));

        }
//        if($_POST['end']!=''){//时间
//            $where['a.exam_time'] =array('<=',$_POST['end']);
//        }

        $where['a.exam_team_id'] = session('loginSession')['team_id'];
        $res = Db::table('up_exam')->alias('a')
            ->join('up_u_user u','u.user_id = a.exam_publisher','left')
            ->where($where)
            ->limit($rows * ($page - 1), $rows)
            ->field('u.user_username,a.*')
            ->order('a.exam_time DESC')
            ->select();
        $total =Db::table('up_exam')->alias('a')
            ->join('up_u_user u','u.user_id = a.exam_publisher','left')
            ->where($where)
            ->count();
        $uid = session('loginSession')['user_id'];
        foreach ($res as $key=>&$vo){
            if($vo['exam_publisher']==$uid){//判断登录的用户和这个课程发布的用户是否是同一个人
                $vo['is_release'] = 1;//同一个人的话就是有发布和取消发布的权限
                $vo['is_delete'] = 1;//同一个人的话就是有删除权限
                $vo['is_update'] = 1;//同一个人的话就是有删除权限
                $vo['is_see'] = 1;//同一个人的话就是有删除权限
            }else{
                $vo['is_release'] = 0;//发布的权限
                $vo['is_delete'] = 0;//删除权限
                $vo['is_update'] = 0;//删除权限
                $vo['is_see'] =0;//同一个人的话就是有删除权限

            }
        }
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

    /**
     * 发布
     */
    public function Confirmation(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['exam_id'] = $cid;
            $data['exam_status'] = 1;//审核通过
            $res =  Db::table('up_exam')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "发布成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "发布失败";
                return json_encode($returnData);
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
            return json_encode($returnData);
        }
    }

    /***
     * 取消发布
     */
    public function QxConfirmation(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['exam_id'] = $cid;
            $data['exam_status'] = 2;//审核通过
            $res =  Db::table('up_exam')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "取消发布成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "取消发布失败";
                return json_encode($returnData);
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
            return json_encode($returnData);
        }
    }

    /**
     * 删除此题库
     */
    public function delConfirmation(){
        $cid = $_POST['cid'];
        $result = Db::table('up_exam')->where('exam_id',$cid)->find();
        $uid = session('loginSession')['user_id'];
        if($uid!=$result['exam_publisher']){
            $returnData['status'] = 0;
            $returnData['msg'] = "不能删除不属于自己的题库";
            return json_encode($returnData);
        }

        if($cid!=''){
            $where['exam_id'] = $cid;
            $res =  Db::table('up_exam')->where($where)->delete();
            $whereMap['subject_exam_id'] = array('IN',$cid);
            Db::table('up_subject')->where($whereMap)->delete();
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "删除成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "删除失败";
                return json_encode($returnData);
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
            return json_encode($returnData);
        }
    }

    /**
     * 查看试题详情
     */
    public function courseInfo(){
        $cid = $_POST['cid'];
        $res = Db::table('up_exam')->alias('a')
                     ->join('up_u_user u','u.user_id = a.exam_publisher')
                    ->where('exam_id',$cid)->field('a.*,u.user_username')->find();
        $this->assign('res',$res);
        return $this->fetch('train/courseInfo');
    }

    /***
     * 编辑页面
     */
    public function updateTrain(){
        $uid = session('loginSession')['user_id'];

        $cid = $_POST['nid'];
        $res = Db::table('up_exam')->where('exam_id',$cid)->find();
        $this->assign('res',$res);
        if($res['exam_publisher']==$uid){
            return $this->fetch('train/updateTrain');
        }else{
            return 1;
        }
    }
    /***
     * 编辑功能
     */
    public function updateInfo(){
        $where['exam_id'] = $_POST['exam_id'];
        if(trim($_POST['exam_name'])==''){
            $returnData['status'] = 0;
            $returnData['msg'] = "试题名称不能为空";
            return json_encode($returnData);
        }
        $data['exam_name'] = $_POST['exam_name'];
        $res = Db::table('up_exam')->where($where)->update($data);
        if($res){
            $returnData['status'] = 1;
            $returnData['msg'] = "修改成功";
            return json_encode($returnData);
        }  else{
            $returnData['status'] = 0;
            $returnData['msg'] = "修改失败";
            return json_encode($returnData);
        }
    }

    /**
     * 获取题目的数据
     */
    public function getSubjectInfo(){
        $where['a.subject_exam_id'] = $_POST['exam_id'];
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if($_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['a.subject_question|u.user_username'] = array('like',"%$keyword%");
        }
        if($_POST['subject_type']!=''){//状态
            $where['a.subject_type'] = $_POST['subject_type'];
        }

        $where['a.subject_team_id'] = session('loginSession')['team_id'];//团队ID
        $res = Db::table('up_subject')->alias('a')
            ->join('up_u_user u','u.user_id = a.subject_user_id')
            ->where($where)
            ->limit($rows * ($page - 1), $rows)
            ->field('u.user_username,a.*')
            ->select();
        $total =Db::table('up_subject')->alias('a')
            ->join('up_u_user u','u.user_id = a.subject_user_id')
            ->where($where)
            ->count();
        $uid = session('loginSession')['user_id'];
        foreach ($res as $key=>&$vo){
            if($vo['subject_user_id']==$uid){//判断登录的用户和这个课程发布的用户是否是同一个人
                $vo['is_delete'] = 1;//同一个人的话就是有删除权限
                $vo['is_update'] = 1;//同一个人的话就是有删除权限
            }else{
                $vo['is_delete'] = 0;//删除权限
                $vo['is_update'] = 0;//同一个人的话就是有删除权限

            }
        }
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }
    /**
     * 删除题目
     */
    public function delSubject(){
        $cid = $_POST['cid'];
        $res = Db::table('up_subject')->where('subject_id',$cid)->delete();
//        Db::table('up_exam_subject')->where('subject_id',$cid)->delete();
        if($res){
            $returnData['status'] = 1;
            $returnData['msg'] = "删除成功";
            return json_encode($returnData);
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "删除失败";
            return json_encode($returnData);
        }
    }
    /**
     * 查看
     */
    public function trainInfo(){
        $cid = $_POST['cid'];
        $res = Db::table('up_subject')->where('subject_id',$cid)->find();
        $this->assign('res',$res);
        return $this->fetch('subject/trainInfo');
    }
    /***
     * 编辑
     */
    public function updateSubject(){
        $cid = $_POST['nid'];
        $res = Db::table('up_subject')->where('subject_id',$cid)->find();
        $this->assign('res',$res);
        $uid = session('loginSession')['user_id'];
        if($res['subject_user_id']==$uid){
            return $this->fetch('subject/updateSubject');
        }else{
            return 1;
        }
    }


    /***
     * 编辑功能
     */
    public function updateSubjectInfo(){
        $where['subject_id'] =$_POST['subject_id'];
        $type =$_POST['subject_type'];

        if($_POST['subject_question']==''){
            $returnData['status'] = 0;
            $returnData['msg'] = "题目名称不能为空";
            return json_encode($returnData);
        }

        if($_POST['subject_introduction']==''){
            $returnData['status'] = 0;
            $returnData['msg'] = "试题解析不能为空";
            return json_encode($returnData);
        }

        if($type==1){ //如果是选择题
            if(($_POST['subject_a']=='')||($_POST['subject_b']=='')||($_POST['subject_c']=='')||($_POST['subject_d']=='')){
                $returnData['status'] = 0;
                $returnData['msg'] = "选择题内容不能为空";
                return json_encode($returnData);
            }
            $data['subject_a'] = $_POST['subject_a'];
            $data['subject_b'] = $_POST['subject_b'];
            $data['subject_c'] = $_POST['subject_c'];
            $data['subject_d'] = $_POST['subject_d'];
        }
        $data['subject_question'] = $_POST['subject_question'];
        $data['subject_introduction'] = $_POST['subject_introduction'];
        $data['subject_answer'] = $_POST['subject_answer'];
        $res = Db::table('up_subject')->where($where)->update($data);
        if($res){
            $returnData['status'] = 1;
            $returnData['msg'] = "修改成功";
            return json_encode($returnData);
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "修改失败";
            return json_encode($returnData);
        }
    }

    /**
* ImportTitle 题库展示页面
* @return 返回展示页面
*/
    public function ImportTitle(){

        return $this->fetch('train/ImportTitle');
    }

    /**
     * insertImportTitle Excel表题库数据导入数据库
     * @return 返回数据存储数据库状态
     */
    public function insertImportTitle(){
        $file_name = $_FILES['excelFile']['name'];//上传的文件名字
        $file_path = $_FILES['excelFile']['tmp_name'];//上传的临时路径
        $file_types = explode('.',$file_name);//切割上传文件名字
        $file_type = $file_types [count ( $file_types ) - 1];//上传的名字后缀
        $first_name = $file_types[0];//去除后缀的文件名
        $uid = session('loginSession')['user_id'];//登录用户的id
        $tid = session('loginSession')['team_id'];//登录用户的id

//        set_time_limit(0);
//       vendor("phpoffice.phpexcel.Classes.PHPExcel");
        vendor("phpoffice.phpexcel.Classes.PHPExcel.IOFactory");
        if( $file_type == 'xls' ){
            $inputFileType = 'Excel5';    //这个是读 xls的
        }else{
            $inputFileType = 'Excel2007';//这个是计xlsx的
        }
        $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($file_path);

        $objWorksheet = $objPHPExcel->getActiveSheet();

        $highestRow = $objWorksheet->getHighestRow();
//        $data = array();//放用户ID的数组
//        Db::startTrans();//开启事物

        /*Excel表基本数据存入up_exam表*/
        $exam_id = $this->getRandChar(32);
//        var_dump($exam_id);die;
        $info = [
            'exam_id'=>$exam_id,
            'exam_name'=>$first_name,
            'exam_time'=>date('Y-m-d H:i:s',time()),
            'exam_publisher'=>$uid,
            'exam_team_id'=>$tid
        ];
        $arr = Db::table('up_exam')
            ->insert($info);
        if($arr) {
            /*循环遍历获取Excel表的数据*/
            for ($is=2;$is<=$highestRow;$is++){
                $a = $objPHPExcel->getActiveSheet()->getCell("A".$is)->getValue();//获取A列的值 试题简介
                $b = $objPHPExcel->getActiveSheet()->getCell("B".$is)->getValue();//获取B列的值  题目
                $c = $objPHPExcel->getActiveSheet()->getCell("C".$is)->getValue();//获取C列的值  选择题答案A
                $d = $objPHPExcel->getActiveSheet()->getCell("D".$is)->getValue();//获取D列的值  选择题答案B
                $e = $objPHPExcel->getActiveSheet()->getCell("E".$is)->getValue();//获取E列的值  选择题答案C
                $f = $objPHPExcel->getActiveSheet()->getCell("F".$is)->getValue();//获取F列的值  选择题答案D
                $g = $objPHPExcel->getActiveSheet()->getCell("G".$is)->getValue();//获取G列的值  答案
                $h = $objPHPExcel->getActiveSheet()->getCell("H".$is)->getValue();//获取H列的值  试题解析

                $subject_id = $this->getRandChar(32);
                /*判断是选择题还是判断题*/
                if ($c !== null || $d !== null || $e !== null || $f !== null) {
                    /*组装选择题的数据*/
                    switch($g)
                    {
                        case 'a':
                            $subject_answer = 1;
                            break;
                        case 'A':
                            $subject_answer = 1;
                            break;
                        case 'b':
                            $subject_answer = 2;
                            break;
                        case 'B':
                            $subject_answer = 2;
                            break;
                        case 'c':
                            $subject_answer = 3;
                            break;
                        case 'C':
                            $subject_answer = 3;
                            break;
                        case 'd':
                            $subject_answer = 4;
                            break;
                        default:
                            $subject_answer = 4;
                            break;
                    }
                    $data = [
                        'subject_id' => $subject_id,
                        'subject_introduction' => $a,
                        'subject_question' => $b,
                        'subject_a' => $c,
                        'subject_b' => $d,
                        'subject_c' => $e,
                        'subject_d' => $f,
                        'subject_explain' => $h,
                        'subject_type' => 1,
                        'subject_user_id' => $uid,
                        'subject_team_id'=>$tid,
                        'subject_answer'=>$subject_answer,
                        'subject_exam_id'=>$exam_id
                    ];
                } else {
                    /*组装判断题的数据*/
                    if ($g == "正确" || $g == "对") {
                        $subject_answer = 1;
                    } else {
                        $subject_answer = 2;
                    }
                    $data = [
                        'subject_question' => $b,
                        'subject_id' => $subject_id,
                        'subject_introduction' => $a,
                        'subject_answer' => $subject_answer,
                        'subject_explain' => $h,
                        'subject_type' => 2,
                        'subject_user_id' => $uid,
                        'subject_team_id'=>$tid,
                        'subject_exam_id'=>$exam_id,
                        'subject_a' => "正确",
                        'subject_b' => "错误"
                    ];
                }
                $res = Db::table('up_subject')
                    ->insert($data);
            }
            if($res){
                $team_id = session('loginSession')['team_id'];//团队ID
                $team_name = session('loginSession')['team_name'];//团队名称
                $where1['team_id'] = $team_id;
                $where1['team_member_remove'] = 2;
                $team_member_user_id = Db::table('up_team_members')->where($where1)->column('team_member_user_id');
                $msg1 = "{\"msg\":\"19\"}";
                $msg = $team_name.'团队发布了新的试题模板';
                $msg_data = array('msg'=>$msg,'code'=>19,'fid'=>$exam_id);
                $code = 19;
                $this->sendJpush(1,$msg,$msg_data,$msg1,$team_member_user_id,$code);

                $returnData['status'] = 1;
                $returnData['msg'] = "添加成功";
            }else{
                Db::table('up_exam')->where('exam_id',$exam_id)->delete();
                $returnData['status'] = 0;
                $returnData['msg'] = "添加失败";
            }
            return json_encode($returnData);
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "添加失败";
        }
    }

    /**
     * createExcel 导出题库表数据生成Excel表
     */
    public function createExcel(){
        $file = 'static/test.xlsx';
        $down = new FileDownload();
        $res = $down->download($file,'题库模板.xlsx',false);
//        $arr = Db::table('up_subject')
//            ->where('subject_user_id',session('loginSession')['user_id'])
//            ->select();
////        dump($arr);die;
//        if(!empty($arr)){
//            // dump($arr);die;
//            header("Content-type:application/vnd.ms-excel");
//            /*规定生成Excel文件名*/
//            header("Content-Disposition:filename=题库.xlsx");
//            /*按照指定的方式生成表数据*/
//            $strexport="试题简介(subject_introduction)\t题目(subject_question)\t答案A(subject_a)\t答案B(subject_b)\t答案C(subject_c)\t答案D(subject_d)\t正确或错误(subject_answer)\t试题解析(subject_explain)\r";
//            foreach ($arr as $row){
//                if($row['subject_type']==2){
//                    if($row['subject_answer']==1){
//                        $subject_answer = "正确";
//                    }else{
//                        $subject_answer = "错误";
//                    }
//                }else{
//                    switch($row['subject_answer'])
//                    {
//                        case 1:
//                            $subject_answer = "A";
//                            break;
//                        case 2:
//                            $subject_answer = "B";
//                            break;
//                        case 3:
//                            $subject_answer = "C";
//                            break;
//                        default:
//                            $subject_answer = "D";
//                            break;
//                    }
//                }
//                $strexport.=$row['subject_introduction']."\t";
//                $strexport.=$row['subject_question']."\t";
//                $strexport.=$row['subject_a']."\t";
//                $strexport.=$row['subject_b']."\t";
//                $strexport.=$row['subject_c']."\t";
//                $strexport.=$row['subject_d']."\t";
//                $strexport.=$subject_answer."\t";
//                $strexport.=$row['subject_explain']."\r";
//            }
//            $strexport=iconv('UTF-8',"GB2312//IGNORE",$strexport);
//            exit($strexport);
//        }else{
//            echo "<script>history.back();window.location.reload();</script>";
//        }
    }

}